//
//  ViewController.m
//  QQ音乐
//
//  Created by Jorn.Wu on 15/7/7.
//  Copyright (c) 2015年 Jorn.Wu. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>

// QP (QQPlayer)

#define QPScreenHeight [UIScreen mainScreen].bounds.size.height
#define QPScreenWidth [UIScreen mainScreen].bounds.size.width
#define QPScreenBound [UIScreen mainScreen].bounds
#define QPNavigationHeight 64
#define QPControlViewHeight 150
#define QPTopBtnHeight 50
#define QPTopBtnWifth 50
#define QPColorWithRGB(r, g, b, a) [UIColor colorWithRed:r / 225.f green:g / 225.f blue:b / 225.f alpha:a]
#define QPTimeLabelFrame CGRectMake(0, 0, 50, 20)


@interface ViewController ()<UIAlertViewDelegate>
@property (nonatomic, strong) AVAudioPlayer *player;
@property (nonatomic, assign) CGFloat alpha;
@property (nonatomic, assign) BOOL isDisplay;
@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, strong) UIImageView *bgImageView;
@property (nonatomic, strong) UIView *navigationView;
@property (nonatomic, strong) UIView *controlView;
@property (nonatomic, strong) UISlider *slider;
@property (nonatomic, strong) UIButton *playBtn;
@property (nonatomic, strong) UILabel *songName;
@property (nonatomic, strong) UILabel *singerName;
@property (nonatomic, strong) UIButton *loveBtn;
@property (nonatomic, strong) NSMutableArray *loveSongs;//收藏的歌曲

@property (nonatomic, strong) NSArray *songAr;
@property (nonatomic, strong) NSArray *songDurationAr;
@property (nonatomic, strong) NSArray *songNameAr;
@property (nonatomic, strong) NSArray *singerNameAr;
@property (nonatomic, strong) NSArray *songImageAr;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int index;
@property (nonatomic, assign) int minute;
@property (nonatomic, assign) int second;

@property (nonatomic, strong) UILabel *timeOfCurrent;
@property (nonatomic, strong) UILabel *timerOfEnd;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self loading];
    [self setting];
    
}
#pragma mark - 加载信息
- (void)loading{
    
    _isDisplay = YES;
    _index = 0;
    self.isPlay = NO;
    self.index = 0;
    [self setAlpha];
    
    [self addBackGroundView];
    [self addNavigationView];
    [self addControlView];
    
    [self loadSongs];
    [self loadSlider];
    [self loadTimeLabel];
}
#pragma mark - 设置播放信息
- (void)setting{
    
    [self loadBackGroundImageWihtIndex:_index];
    [self loadSongNameWihtIndex:_index];
    [self loadSingerNameWihtIndex:_index];
    [self setTimeLabelWithIndex:_index];
    [self setSliderWithIndex:_index];
    [self setPlayerWithIndex:_index];
    
    [self isLoveSong];
    
}

#pragma mark - 加载歌曲
- (void)loadSongs{
    NSBundle *bundle = [NSBundle mainBundle];
    
    NSURL *url0 = [NSURL fileURLWithPath:[bundle pathForResource:@"你不知道的事" ofType:@"mp3"]];
    NSURL *url1 = [NSURL fileURLWithPath:[bundle pathForResource:@"你给我听好" ofType:@"mp3"]];
    NSURL *url2 = [NSURL fileURLWithPath:[bundle pathForResource:@"安静" ofType:@"mp3"]];
    NSURL *url3 = [NSURL fileURLWithPath:[bundle pathForResource:@"遇见" ofType:@"mp3"]];
    self.songAr = @[url0,url1,url2,url3];//歌曲
    
    self.songDurationAr = @[@279,@289,@335,@210];//歌曲时长
    self.songNameAr = @[@"你不知道的事", @"你给我听好", @"安静", @"遇见"];//歌名
    self.singerNameAr = @[@"王力宏",@"陈奕迅",@"周杰伦",@"孙燕姿"];//歌手
    
    UIImage *img0 = [UIImage imageNamed:@"wanglihong.jpg"];
    UIImage *img1 = [UIImage imageNamed:@"chenyixun.jpg"];
    UIImage *img2 = [UIImage imageNamed:@"zhoujielun.jpg"];
    UIImage *img3 = [UIImage imageNamed:@"yanzi.jpg"];
    self.songImageAr = @[img0,img1,img2,img3];//图片
}
#pragma mark - 设置透明度
- (void)setAlpha{
    self.alpha = 0.6;
}
#pragma mark - 添加背景视图
- (void)addBackGroundView{
    
    _bgImageView          = [[UIImageView alloc]initWithFrame:QPScreenBound];
    
    UIButton *bgBtn       = [[UIButton alloc] initWithFrame:QPScreenBound];
    bgBtn.backgroundColor = [UIColor clearColor];
    [bgBtn addTarget:self action:@selector(setHidden) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_bgImageView];
    [self.view addSubview:bgBtn];
}
#pragma mark - 加载背景图片
- (void)loadBackGroundImageWihtIndex:(int)index{
    _bgImageView.image = _songImageAr[index];
}
#pragma mark - 控制上下两视图的隐藏和显示
- (void)setHidden{
    _isDisplay = !_isDisplay;
    if (!_isDisplay) {
        self.navigationView.hidden = NO;
        self.controlView.hidden    = NO;
    }else {
        self.navigationView.hidden = YES;
        self.controlView.hidden    = YES;
    }
}
#pragma mark - 添加导航视图
- (void)addNavigationView{
    _navigationView                 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, QPScreenWidth, QPNavigationHeight)];
    _navigationView.backgroundColor = [UIColor blackColor];
    _navigationView.alpha           = _alpha;
    
    UIButton *leftBtn = [[UIButton alloc] initWithFrame:CGRectMake(5, 15, QPTopBtnWifth, QPTopBtnWifth)];//5是边距，20是上边距（状态栏）
    [leftBtn setImage:[UIImage imageNamed:@"top_back_white@2x.png" ] forState:UIControlStateNormal];
    
    _songName               = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 25)];
    _songName.center        = CGPointMake(QPScreenWidth * 0.5, 15 + 25 * 0.5);
    _songName.textAlignment = NSTextAlignmentCenter;
    _songName.textColor     = [UIColor greenColor];
    _songName.font          = [UIFont systemFontOfSize:25];
    
    
    _singerName               = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 20)];
    _singerName.center        = CGPointMake(QPScreenWidth * 0.5, 12 + 25 + 25 * 0.5);
    _singerName.textAlignment = NSTextAlignmentCenter;
    _singerName.textColor     = [UIColor whiteColor];
    _singerName.font          = [UIFont systemFontOfSize:15];
    
    _loveBtn = [[UIButton alloc] initWithFrame:CGRectMake(QPScreenWidth - QPTopBtnWifth - 5, 15, QPTopBtnWifth, QPTopBtnHeight)];
    [_loveBtn setImage:[UIImage imageNamed:@"playing_btn_love_h@2x.png"] forState:UIControlStateNormal];
    [_loveBtn setImage:[UIImage imageNamed:@"playing_btn_in_myfavor_h@2x.png"] forState:UIControlStateSelected];
    [_loveBtn addTarget:self action:@selector(loveBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [_navigationView addSubview:leftBtn];
    [_navigationView addSubview:_singerName];
    [_navigationView addSubview:_songName];
    [_navigationView addSubview:_loveBtn];
    [self.view addSubview:_navigationView];
}
#pragma mark - 收藏按钮的响应方法
- (NSMutableArray *)loveSongs{
    if (_loveSongs == nil) {
        _loveSongs = [NSMutableArray arrayWithCapacity:_songNameAr.count];
    }
    return _loveSongs;
}
#pragma mark - 是否为收藏的歌曲
- (void)isLoveSong{
    if ([_loveSongs containsObject:_songNameAr[_index]]) {
        _loveBtn.selected = YES;
        NSLog(@"这首歌已收藏");
        
    }else {
        _loveBtn.selected = NO;
        NSLog(@"这首歌未收藏");
    }
}
#pragma mark - 收藏按钮的响应方法
- (void)loveBtnAction:(UIButton *)button{
    button.selected = !button.selected;
    if (button.selected) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定要取消收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        [alert show];
    }
}
#pragma mark - 提示框
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (alertView.numberOfButtons == 2 && buttonIndex == 1) {//取消 放弃收藏
        _loveBtn.selected = YES;
    }else if ((alertView.numberOfButtons == 1)) {//确定收藏
        [self.loveSongs addObject:_songNameAr[_index]];//将该歌曲添加到收藏列表
        return;
    }else {//确定放弃收藏
        _loveBtn.selected = NO;
        [_loveSongs removeObject:_songNameAr[_index]];//将该歌曲从收藏列表去除
    }

}
#pragma mark - 加载歌曲的名字和歌手名字
- (void)loadSongNameWihtIndex:(int)index{
    _songName.text = _songNameAr[index];
}
- (void)loadSingerNameWihtIndex:(int)index{
    _singerName.text = _singerNameAr[index];
}
#pragma mark - 添加控制视图
- (void)addControlView{
    _controlView                 = [[UIView alloc] initWithFrame:CGRectMake(0,
                                                                            QPScreenHeight - QPControlViewHeight,
                                                                            QPScreenWidth,
                                                                            QPControlViewHeight)];
    _controlView.backgroundColor = [UIColor blackColor];
    _controlView.alpha           = _alpha;
    
    _playBtn = [[UIButton alloc] initWithFrame:CGRectMake((QPScreenWidth - 70) * 0.5, (_controlView.bounds.size.height - 70) * 0.5, 70, 70)];
    
    [_playBtn setImage:[UIImage imageNamed:@"playing_btn_play_n@2x.png"] forState:UIControlStateNormal];
    [_playBtn setImage:[UIImage imageNamed:@"playing_btn_play_h@2x.png"] forState:UIControlStateHighlighted];
    [_playBtn addTarget:self action:@selector(playBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *preBtn = [[UIButton alloc] initWithFrame:CGRectMake(60, (_controlView.bounds.size.height - 60) * 0.5, 60,60)];
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(QPScreenWidth - 60 - 60, (_controlView.bounds.size.height - 60) * 0.5, 60, 60)];
    
    [preBtn setImage:[UIImage imageNamed:@"playing_btn_pre_n@2x.png"] forState:UIControlStateNormal];
    [preBtn setImage:[UIImage imageNamed:@"playing_btn_pre_h@2x.png"] forState:UIControlStateHighlighted];
    [preBtn addTarget:self action:@selector(previousBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    [nextBtn setImage:[UIImage imageNamed:@"playing_btn_next_n@2x.png"] forState:UIControlStateNormal];
    [nextBtn setImage:[UIImage imageNamed:@"playing_btn_next_h@2x.png"] forState:UIControlStateHighlighted];
    [nextBtn addTarget:self action:@selector(nextBtnAction) forControlEvents:UIControlEventTouchUpInside];
    
    [_controlView addSubview:preBtn];
    [_controlView addSubview:nextBtn];
    [_controlView addSubview:_playBtn];
    [self.view addSubview:_controlView];
}
#pragma mark - 加载进度条
- (void)loadSlider{
    _slider        = [[UISlider alloc] initWithFrame:CGRectMake(0, 0, QPScreenWidth, 10)];
    _slider.center = CGPointMake(_controlView.bounds.size.width * 0.5, 0);
    [_slider setThumbImage:[UIImage imageNamed:@"playing_slider_thumb@2x.png" ] forState:UIControlStateNormal];
    [_slider setThumbImage:[UIImage imageNamed:@"playing_slider_thumb@2x.png" ] forState:UIControlStateHighlighted];
    _slider.minimumTrackTintColor = [UIColor greenColor];
    _slider.maximumTrackTintColor = [UIColor whiteColor];
    _slider.alpha                 = _alpha;
    [_controlView addSubview:_slider];
    [_slider addTarget:self action:@selector(sliderValueChange) forControlEvents:UIControlEventAllEvents];

}
#pragma mark - 根据歌曲的时长设置进度的的属性
- (void)setSliderWithIndex:(int)index{
    _slider.maximumValue = [self.songDurationAr[index] intValue];
    _slider.minimumValue = 0;
    _slider.value        = 0;
}
#pragma mark - 更新进度条的值和当期时间显示
- (void)updateSliderValue{
    _second                 = (int)self.slider.value % 60;
    _minute                 = (int)self.slider.value / 60;
    self.timeOfCurrent.text = [NSString stringWithFormat:@"%02d:%02d",_minute,_second];
    self.slider.value ++;
    if (self.slider.value == [self.songDurationAr[_index] integerValue]) {
        [self nextBtnAction];//下一曲
    }
}

#pragma mark - 加载和设置进度条时间显示
- (void)loadTimeLabel{
    _timeOfCurrent               = [[UILabel alloc]initWithFrame:QPTimeLabelFrame];
    _timeOfCurrent.text          = @"00:00";
    _timeOfCurrent.textAlignment = NSTextAlignmentRight;
    _timeOfCurrent.textColor     = [UIColor greenColor];
    _timeOfCurrent.center        = CGPointMake(5 + QPTimeLabelFrame.size.width * 0.5,20);
    _timeOfCurrent.alpha         = _alpha;
    
    _timerOfEnd                  = [[UILabel alloc]initWithFrame:QPTimeLabelFrame];
    _timerOfEnd.text             = @"00:00";
    _timerOfEnd.textAlignment    = NSTextAlignmentLeft;
    _timerOfEnd.textColor        = [UIColor greenColor];
    _timerOfEnd.center           = CGPointMake(QPScreenWidth - 5 - QPTimeLabelFrame.size.width * 0.5,20);
    _timerOfEnd.alpha            = _alpha;
    
    [_controlView addSubview:_timeOfCurrent];
    [_controlView addSubview:_timerOfEnd];
    
}
#pragma mark - 根据歌曲的时长设置时间的显示
- (void)setTimeLabelWithIndex:(int)index{
    
    NSInteger endTime    = [_songDurationAr[index] integerValue];
    NSInteger tempMinute = endTime / 60;
    NSInteger tempSecond = endTime % 60;
    
    _timerOfEnd.text     = [NSString stringWithFormat:@"%02li:%02li",tempMinute,tempSecond];
    
    [self updateSliderValue];
    
}
#pragma mark - 上一首控制按钮响应方法
- (void)previousBtnAction{
    _index--;
    
    if (_index < 0) {
        _index = (int)([self.songAr count] - 1);
    }
    //    确保能播放
    [self.timer invalidate];//先关掉上一个计时器
    [self setting];//重新加载信息
    
    if (_isPlay == NO) {
        [self playBtnAction];//播放
    }else {
        _isPlay = NO;//应为在播放按钮里还取反一次
        [self playBtnAction];
    }
    
}
#pragma mark - 下一首控制按钮响应方法
- (void)nextBtnAction{
    _index++;
    
    if (_index == [self.songAr count]) {
        _index = 0;
    }
    //    确保能播放
    [self.timer invalidate];//先关掉上一个计时器
    [self setting];//重新加载信息
    
    if (_isPlay == NO) {
        [self playBtnAction];//播放
    }else {
        _isPlay = NO;//应为在播放按钮里还取反一次
        [self playBtnAction];
    }
    
}
#pragma mark - 播放控制按钮响应方法
- (void)playBtnAction{
    _isPlay = !_isPlay;
    
    if (_isPlay == NO) {
        [_playBtn setImage:[UIImage imageNamed:@"playing_btn_play_n@2x.png"] forState:UIControlStateNormal];
        [self.player pause];
        [self.timer invalidate];//关闭计时器
        
    }else {
        [_playBtn setImage:[UIImage imageNamed:@"playing_btn_pause_n@2x.png"] forState:UIControlStateNormal];

        _timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                  target:self
                                                selector:@selector(updateSliderValue)
                                                userInfo:nil
                                                 repeats:YES];
        [self.player play];//放在最后，先更新好数据才播放
    }
    
}

#pragma mark - 设置播放器
- (void)setPlayerWithIndex:(int)index{
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:_songAr[_index] error:nil];
    
}
#pragma mark - slider的响应方法
- (void)sliderValueChange{
    [self updateSliderValue];
    self.player.currentTime = self.slider.value;
}


@end
